﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ywxt.Common;

namespace ZJK.Controllers.ExtractManage
{
    using System.ComponentModel.DataAnnotations;
    using NHibernate.Criterion;
    using DB_NH;
    using Models.ExtractManage;

    [Authorize]
    public class ExtractController : Controller
    {
        //
        // GET: /Extract/
        /// <summary>
        /// 初始化抽取首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            vmExtractIndex _model = new vmExtractIndex();

            _model.categorys = getCategorys();

            return View(_model);
        }

        #region 专家抽取记录打印
        /// <summary>
        /// 打印抽取记录表哥
        /// </summary>
        /// <param name="extractID"></param>
        /// <returns></returns>
        public ActionResult PrintExtract(string extractID)
        {
            /*
            vmPrintExtract _model = new vmPrintExtract();

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            using (var transaction = session.BeginTransaction())
            {
                //查询抽取记录
                var _r = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract>()
                    .Where(c => c.IsValid == 1 && c.Id == extractID)
                    .OrderBy(c => c.CreateDate).Desc()
                    .Take(1)
                    .SingleOrDefault();

                if (_r != null)
                {
                    _model.ExtractDate = _r.extract_date;
                    _model.ExtractId = _r.Id;

                    string _proj_title = string.Empty;
                    foreach (var _p in _r.zj_extract_projects)
                    {
                        if (_p.is_valid == 1 && _p.is_leaf == 1)
                        {
                            if (string.IsNullOrEmpty(_proj_title))
                            {
                                _proj_title = "[" + _p.proj_code + "]" + _p.proj_name;
                            }
                            else
                            {
                                _proj_title = "；[" + _p.proj_code + "]" + _p.proj_name;
                            }
                        }
                    }
                    _model.ProjectTitle = _proj_title;
                }

                var _details = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract_detail>()
                    .Where(c => c.IsValid == 1 && c.extract == _r)
                    .OrderBy(c => c.order_flag).Asc()
                    .List();
                foreach (var _d in _details)
                {
                    var _e = new ExtractExpert()
                    {
                        Company = _d.zj_company,
                        ExpertId = _d.expert.Id,
                        ExtractExpertId = _d.Id,
                        isCome = _d.is_selected,
                        Name = _d.zj_name,
                        Phone = _d.zj_mobile,
                        Remark = _d.un_selected_msg,
                        Title = _d.zj_title
                    };
                    _model.Experts.Add(_e);
                }
            }
            
            return View(_model);
             */

            return View();
        }

        /// <summary>
        /// 根据抽取ID，获取要抽取
        /// </summary>
        /// <param name="extractID"></param>
        /// <returns></returns>
        public JsonResult GetExtractInfo(string extractID)
        {
            JsonResultForPrintExtract _returnValue = new JsonResultForPrintExtract();

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            using (var transaction = session.BeginTransaction())
            {
                //查询抽取记录
                var _r = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract>()
                    .Where(c => c.IsValid == 1 && c.Id == extractID)
                    .OrderBy(c => c.CreateDate).Desc()
                    .Take(1)
                    .SingleOrDefault();

                if (_r != null)
                {
                    _returnValue.ExtractInfo.ExtractDate = _r.extract_date;
                    _returnValue.ExtractInfo.ExtractId = _r.Id;

                    string _proj_title = string.Empty;
                    foreach (var _p in _r.zj_extract_projects)
                    {
                        if (_p.is_valid == 1 && _p.is_leaf == 1)
                        {
                            if (string.IsNullOrEmpty(_proj_title))
                            {
                                _proj_title = "[" + _p.proj_code + "]" + _p.proj_name;
                            }
                            else
                            {
                                _proj_title = "；[" + _p.proj_code + "]" + _p.proj_name;
                            }
                        }
                    }
                    _returnValue.ExtractInfo.ProjectTitle = _proj_title;
                }

                var _details = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract_detail>()
                    .Where(c => c.IsValid == 1 && c.extract == _r)
                    .OrderBy(c => c.order_flag).Asc()
                    .List();
                foreach (var _d in _details)
                {
                    var _e = new ExtractExpertForPrint()
                    {
                        Company = _d.zj_company,
                        ExpertId = _d.expert.Id,
                        ExtractExpertId = _d.Id,
                        isCome = _d.is_selected,
                        Name = _d.zj_name,
                        Phone = _d.zj_mobile,
                        Remark = _d.un_selected_msg,
                        Title = _d.zj_title
                    };
                    _returnValue.ExtractInfo.Experts.Add(_e);
                }
            }

            return Json(_returnValue);
        }

        /// <summary>
        /// 打印抽取记录表用到的ViewModal
        /// </summary>
        public class vmPrintExtract
        {
            /// <summary>
            /// 抽取ID
            /// </summary>
            public string ExtractId { get; set; }

            /// <summary>
            /// 抽取时间
            /// </summary>
            public DateTime ExtractDate { get; set; }

            /// <summary>
            /// 抽取时间——字符串
            /// </summary>
            public string ExtractDate_str
            {
                get { return ExtractDate.ToString("yyyy年MM月dd日HH时"); }
                set { }
            }

            /// <summary>
            /// 抽取的项目标题
            /// </summary>
            public string ProjectTitle { get; set; }

            /// <summary>
            /// 抽取的专家记录
            /// </summary>
            public List<ExtractExpert> Experts { get; set; }

            public vmPrintExtract()
            {
                Experts = new List<ExtractExpert>();
            }
        }

        /// <summary>
        /// 抽取记录返回的JSON类定义
        /// </summary>
        public class JsonResultForPrintExtract : ZJK.Models.clsCommonJsonResult
        {
            public ExtractInfoForPrint ExtractInfo { get; set; }

            public JsonResultForPrintExtract()
            {
                ExtractInfo = new ExtractInfoForPrint();
            }
        }

        /// <summary>
        /// 打印的抽取记录
        /// </summary>
        public class ExtractInfoForPrint
        {
            /// <summary>
            /// 抽取ID
            /// </summary>
            public string ExtractId { get; set; }

            /// <summary>
            /// 抽取时间
            /// </summary>
            public DateTime ExtractDate { get; set; }

            /// <summary>
            /// 抽取时间——字符串
            /// </summary>
            public string ExtractDate_str
            {
                get { return ExtractDate.ToString("yyyy年MM月dd日HH时"); }
                set { }
            }

            /// <summary>
            /// 抽取的项目标题
            /// </summary>
            public string ProjectTitle { get; set; }

            /// <summary>
            /// 抽取的专家记录
            /// </summary>
            public List<ExtractExpertForPrint> Experts { get; set; }

            public ExtractInfoForPrint()
            {
                Experts = new List<ExtractExpertForPrint>();
            }
        }

        /// <summary>
        /// 抽取专家信息
        /// </summary>
        public class ExtractExpertForPrint
        {
            /// <summary>
            /// 抽取专家记录的ID
            /// </summary>
            public string ExtractExpertId { get; set; }

            /// <summary>
            /// 专家Id
            /// </summary>
            public string ExpertId { get; set; }

            /// <summary>
            /// 专家名
            /// </summary>
            public string Name { get; set; }

            /// <summary>
            /// 专家工作单位
            /// </summary>
            public string Company { get; set; }

            /// <summary>
            /// 专家联系方式
            /// </summary>
            public string Phone { get; set; }

            /// <summary>
            /// 专家职称职务
            /// </summary>
            public string Title { get; set; }

            /// <summary>
            /// 专家是否参与
            /// </summary>
            public int isCome { get; set; }

            /// <summary>
            /// 专家是否参与_字符串
            /// </summary>
            public string isCome_str
            {
                get
                {
                    if (isCome == 1)
                    {
                        return "是";
                    }
                    else
                    {
                        return "否";
                    }
                }
                set { }
            }

            /// <summary>
            /// 备注
            /// </summary>
            public string Remark { get; set; }
        }
        #endregion

        /// <summary>
        /// 根据关键字获取项目列表
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult getCategorysJson()
        {
            var _returnValue = new List<vmCategoryJson>();

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            using (var transaction = session.BeginTransaction())
            {
                var _records = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_category>()
                    .Where(c => c.IsValid == 1)
                    .OrderBy(c => c.category_code).Asc()
                    .List();

                if (_records != null)
                {
                    foreach (var _record in _records)
                    {
                        vmCategoryJson _item = new vmCategoryJson()
                        {
                            id = _record.Id,
                            name = "[" + _record.category_code + "]" + _record.category_name
                        };

                        if (_record.pre_category != null)
                        {
                            _item.pId = _record.pre_category.Id;
                        }
                        else
                        {
                            _item.pId = "0";
                        }

                        _returnValue.Add(_item);
                    }
                }
            }

            return Json(_returnValue, JsonRequestBehavior.AllowGet);
        }

        private List<vmCategory> getCategorys()
        {
            var _returnValue = new List<vmCategory>();

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    var _records = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_category>()
                        .Where(c => c.IsValid == 1)
                        .OrderBy(c => c.category_code).Asc()
                        .List();

                    if (_records != null)
                    {
                        foreach (var _record in _records)
                        {
                            vmCategory _item = new vmCategory()
                            {
                                categoryId = _record.Id,
                                categoryCode = _record.category_code,
                                categoryName = _record.category_name
                            };

                            if (_record.pre_category != null)
                            {
                                _item.parentId = _record.pre_category.Id;
                            }
                            else
                            {
                                _item.parentId = string.Empty;
                            }

                            _returnValue.Add(_item);
                        }
                    }
                }
            }

            return _returnValue;
        }

        /// <summary>
        /// 提交时的操作
        /// </summary>
        /// <param name="_model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Index(vmExtractIndex _model)
        {
            #region 处理抽取相关项目
            if (_model.selectedProjectIDs != null && _model.selectedProjectIDs.Length >= 0)
            {
                string msg = "项目IDs：";
                foreach (var _str in _model.selectedProjectIDs)
                {
                    msg += _str + ",";
                }
                TempData[Common.CONST_TEMPDATA_INF] = msg;
            }
            #endregion

            #region 处理抽取方式
            /*
            if (_model.selectedProfessions != null && _model.selectedProfessions.Length > 0)
            {
                string msg = "专家专业：";
                foreach (var _str in _model.selectedProfessions)
                {
                    msg += _str + ",";
                }
                TempData[Common.CONST_TEMPDATA_INF] += "<br />" + msg;
            }

            if (_model.selectedCategorys != null && _model.selectedCategorys.Length > 0)
            {
                string msg = "专家分类：";
                foreach (var _str in _model.selectedCategorys)
                {
                    msg += _str + ",";
                }
                TempData[Common.CONST_TEMPDATA_INF] += "<br />" + msg;
            }
             */

            if (!string.IsNullOrEmpty(_model.selectedCategorys))
            {
                TempData[Common.CONST_TEMPDATA_INF] += @"
专家分类：" + _model.selectedCategorys;
            }
            if (!string.IsNullOrEmpty(_model.selectedProfessions))
            {
                TempData[Common.CONST_TEMPDATA_INF] += @"
专家专业：" + _model.selectedProfessions;
            }
            #endregion

            _model.categorys = getCategorys();

            return View(_model);
        }

        /// <summary>
        /// 根据关键字获取项目列表
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetProjects(string keyword)
        {
            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    #region 获取项目信息
                    string ss = keyword;
                    if (keyword.IndexOf('/') >= 0)
                    {
                        ss = keyword.Substring(0, keyword.IndexOf('/'));
                    }

                    var _projects = session.QueryOver<DB_NH.DB_Model.ywxt.t_project>()
                        .Where(c => c.is_valid == 1 && c.is_leaf == 1 && (
                            c.proj_code.IsLike("%" + ss) || c.proj_code.IsLike("%" + ss + "/%") || c.proj_name.IsLike("%" + ss + "%")))
                        .OrderBy(c => c.ProjectYear).Desc()
                        .OrderBy(c => c.proj_order_flag).Desc()
                        .OrderBy(c => c.proj_code).Asc()
                        .Take(10)
                        .List();

                    List<vmProject> projects = new List<vmProject>();

                    foreach (var _e in _projects)
                    {
                        string _proj_code = _e.proj_code;
                        /*
                        if (_proj_code.IndexOf('/') >= 0)
                        {
                            //项目编号带有“/”，则编号截取第一个"/"字符前5位
                            _proj_code = _proj_code.Remove(0, _proj_code.IndexOf('/') - 5);
                        }
                        else
                        {
                            _proj_code = _proj_code.Remove(0, _proj_code.Length - 5);
                        }
                         */
                        vmProject _p = new vmProject()
                        {
                            projectId = _e.proj_id,
                            projectCode = _proj_code,
                            projectName = _e.proj_name
                        };

                        projects.Add(_p);
                    }

                    transaction.Commit();
                    return Json(projects);
                    #endregion
                }
            }
        }

        /// <summary>
        /// 根据关键字获取专家分类列表
        /// </summary>
        /// <param name="kwProfessions">关键字专业，以逗号分隔</param>
        /// <param name="kwCategoryIDs">关键字专业分类，以逗号分隔</param>
        /// <returns></returns>
        public JsonResult GetExperts(string kwProfessions, string kwCategoryIDs)
        {
            List<vmExpert> vmExperts = new List<vmExpert>();

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    if (!string.IsNullOrEmpty(kwProfessions))
                    {
                        string[] professions = kwProfessions.Split(new char[] { ',', ';' });
                        if (professions.Length > 0)
                        {
                            #region 按专家专业进行查询专家列表，专业以逗号进行分割
                            var _query = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_expert>()
                                .Where(c => c.IsValid == 1);

                            //添加or
                            var x = new Disjunction();
                            foreach (string _p in professions)
                            {
                                string temp = "%" + _p + "%";
                                x.Add(Restrictions.On<DB_NH.DB_Model.ZJK.ZJ_expert>(c => c.zj_professional).IsLike(temp, MatchMode.Anywhere));
                            }
                            #endregion

                            #region 循环生成viewmodel专家类
                            var experts = _query.And(x)
                                .List();

                            foreach (var expert in experts)
                            {
                                vmExpert _exp = new vmExpert()
                                {
                                    expertId = expert.Id,
                                    expertMobile = expert.zj_mobile,
                                    expertName = expert.zj_name,
                                    expertPhone = expert.zj_mobile,
                                    expertProfession = expert.zj_professional,
                                    expertTitle = expert.zj_title,
                                    expertUnit = expert.zj_company
                                };

                                foreach (var category in expert.zj_categorys)
                                {
                                    if (string.IsNullOrEmpty(_exp.expertCategorys))
                                    {
                                        _exp.expertCategorys = _exp.expertCategorys;
                                    }
                                    else
                                    {
                                        _exp.expertCategorys += "," + _exp.expertCategorys;
                                    }
                                }

                                vmExperts.Add(_exp);
                            }
                            #endregion

                            transaction.Commit();
                        }
                    }
                    else if (!string.IsNullOrEmpty(kwCategoryIDs))
                    {
                        #region 按专家分类进行查询专家列表，专家分类以逗号进行分割
                        string[] categoryids = kwCategoryIDs.Split(new char[] { ',', ';' });

                        var _categorys = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_category>()
                            .Where(c => c.IsValid == 1 && c.Id.IsIn(categoryids))
                            .List();

                        //获取
                        foreach (var _c in _categorys)
                        {
                            foreach (var zj_expert in _c.zj_experts)
                            {
                                bool hasItem = false;

                                foreach (var _e in vmExperts)
                                {
                                    if (_e.expertId.Equals(zj_expert.Id))
                                    {
                                        hasItem = true;
                                        break;
                                    }
                                }

                                if (!hasItem)
                                {
                                    vmExpert _exp = new vmExpert()
                                    {
                                        expertId = zj_expert.Id,
                                        expertMobile = zj_expert.zj_mobile,
                                        expertName = zj_expert.zj_name,
                                        expertPhone = zj_expert.zj_tele_work,
                                        expertProfession = zj_expert.zj_professional,
                                        expertTitle = zj_expert.zj_title,
                                        expertUnit = zj_expert.zj_company
                                    };
                                    vmExperts.Add(_exp);
                                }
                            }
                        }
                        #endregion

                        transaction.Commit();
                    }

                }
            }

            return Json(vmExperts);
        }


        /// <summary>
        /// 根据项目关键字获取内定专家列表
        /// </summary>
        /// <param name="kwProjectIds">关键字项目，以逗号分隔</param>
        /// <returns></returns>
        public JsonResult GetExpertIDsn(string kwProjectIds)
        {
            List<string> vmExpertIds = new List<string>();

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    if (!string.IsNullOrEmpty(kwProjectIds))
                    {
                        string[] project_ids = kwProjectIds.Split(new char[] { ',', ';' });
                        if (project_ids.Length > 0)
                        {
                            #region 按专家专业进行查询专家列表，专业以逗号进行分割
                            var _projects = session.QueryOver<DB_NH.DB_Model.ywxt.t_project>()
                                .Where(c => c.is_valid == 1 && c.proj_id.IsIn(project_ids))
                                .List();
                            #endregion

                            #region 循环项目，获取备选设置，获取最晚的抽取设置
                            DB_NH.DB_Model.ZJCQ.ZJ_extract_bak _thisExtractBak = null;

                            //循环每个项目，获取项目的所有抽取备选记录
                            foreach (var _proj in _projects)
                            {
                                foreach (var _extract_bak in _proj.proj_extract_baks)
                                {
                                    if (_thisExtractBak == null)
                                    {
                                        _thisExtractBak = _extract_bak;
                                    }
                                    else
                                    {
                                        if (_extract_bak.CreateDate > _thisExtractBak.CreateDate)
                                        {
                                            _thisExtractBak = _extract_bak;
                                        }
                                    }
                                }
                            }
                            #endregion

                            #region 获取当前取得的最后的备选记录所对应的详细备选专家记录
                            if (_thisExtractBak != null && _thisExtractBak.details.Count > 0)
                            {
                                var _details = _thisExtractBak.details.OrderBy(c => c.order_flag);
                                foreach (var _detail in _details)
                                {
                                    vmExpertIds.Add(_detail.expert.Id);
                                }
                            }
                            #endregion

                            transaction.Commit();
                        }
                    }
                }
            }

            return Json(vmExpertIds);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult New()
        {
            return View();
        }

        /// <summary>
        /// 第一步，选择抽取操作关联的项目
        /// </summary>
        /// <returns></returns>
        public ActionResult Step1(string pid)
        {
            vmStep1 model = new vmStep1();

            if (!string.IsNullOrEmpty(pid))
            {
                var sessionFactory = SessionFactory.GetCurrentFactory();
                using (var session = sessionFactory.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {
                        try
                        {
                            var p = session.QueryOver<DB_NH.DB_Model.ywxt.t_project>()
                                .Where(c => c.proj_id == pid && c.is_valid == 1)
                                .SingleOrDefault();
                            if (p != null)
                            {
                                model.projectCode = p.proj_code;
                            }
                            transaction.Commit();
                        }
                        catch (Exception)
                        {
                            transaction.Rollback();
                            throw;
                        }
                    }
                }
            }

            return View(model);
        }

        /// <summary>
        /// Step1后，点击新建抽取记录按钮，为选中的项目进行新建抽取记录操作，操作步骤：
        /// 1、获取项目列表；
        /// 2、生成一条新的抽取记录；
        /// </summary>
        /// <param name="selectedProjectIDs">所选中的项目ID，以逗号分割</param>
        /// <returns></returns>
        public ActionResult NewExtractForSelectedProjects(string selectedProjectIDs)
        {
            vmNewExtractForSelectedProjects _model = new vmNewExtractForSelectedProjects();

            //绑定项目ID，获取项目信息
            _model.selectedProjetcIDs = selectedProjectIDs;
            _model.getProjects();

            //生成抽取记录的标题
            if (_model.extractRecord_selectedProjects.Count > 0)
            {
                _model.extractRecord_Title = "抽取（" + _model.extractRecord_selectedProjects[0].projectCode + "）等" +
                    _model.extractRecord_selectedProjects.Count.ToString() + "个项目的评审专家。";

            }

            return View(_model);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public JsonResult DeleteExtract(string extractID)
        {
            ZJK.Models.clsCommonJsonResult _resultValue = new Models.clsCommonJsonResult();

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    try
                    {
                        #region 删除指定的抽取记录，设置为无效
                        var _r = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract>()
                            .Where(c => c.IsValid == 1 && c.Id == extractID)
                            .SingleOrDefault();
                        if (_r == null)
                        {
                            throw new Exception("抽取信息未找到。");
                        }

                        _r.IsValid = 0;
                        session.SaveOrUpdate(_r);
                        #endregion

                        transaction.Commit();
                    }
                    catch (Exception _ex)
                    {
                        _resultValue.ISOK = false;
                        _resultValue.MESSAGE = _ex.Message;
                        transaction.Rollback();
                    }
                }
            }

            return Json(_resultValue, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 保存当前抽取记录
        /// </summary>
        /// <param name="_model"></param>
        /// <returns></returns>
        public ActionResult SaveNewExtract(vmNewExtractForSelectedProjects _model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    #region 获取当前登录用户

                    string _this_user_name_en = Common.getAuthenticatedUser(User).Name;
                    string _this_user_name_cn = Common.getAuthenticatedUser(User).DisplayName;

                    #endregion

                    #region 保存当前抽取记录
                    if (_model != null)
                    {
                        _model.saveExtract(_this_user_name_en);
                        TempData[Common.CONST_TEMPDATA_INF] = @"保存抽取记录成功。";
                        return RedirectToAction("Step1");
                    }
                    #endregion
                }
                catch (Exception ex)
                {
                    TempData[Common.CONST_TEMPDATA_INF] = @"保存抽取记录失败，请联系管理员获取错误信息。";
                    TempData[Common.CONST_TEMPDATA_ERR] = ex.Message;
                    return RedirectToAction("Step1");
                }
            }

            return View(_model);
        }

        /// <summary>
        /// 查看抽取结果
        /// </summary>
        /// <param name="id">传入的抽取记录ID</param>
        /// <returns></returns>
        public ActionResult viewExtractRecord(string id)
        {
            ZJK.Models.ExtractManage.vmExtractRecord extRecord = new ZJK.Models.ExtractManage.vmExtractRecord()
            {
                extractID = id,
                experts = new List<ExtractExpert>(),
                OPDate = DateTime.Now,
                OPUser = string.Empty,
                projs = new List<ExtractProject>()
            };

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    try
                    {
                        #region 查询并构建抽取记录关联的项目列表
                        var record = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract>()
                            .Fetch(c => c.zj_extract_projects).Eager()
                            .Where(c => c.Id == id)
                            .SingleOrDefault();

                        if (record != null && record.zj_extract_projects.Count > 0)
                        {
                            #region 设置抽取用户
                            extRecord.OPUser = record.user.user_truename_cn;
                            extRecord.OPDate = record.CreateDate;
                            #endregion

                            foreach (var _p in record.zj_extract_projects)
                            {
                                if (_p != null && _p.is_valid == 1)
                                {
                                    var _proj = new ZJK.Models.ExtractManage.ExtractProject()
                                        {
                                            proj_id = _p.proj_id,
                                            proj_code = _p.proj_code,
                                            proj_name = _p.proj_name
                                        };

                                    extRecord.projs.Add(_proj);
                                }
                            }
                        }
                        else
                        {
                            throw new Exception("记录未找到。");
                        }

                        #endregion

                        #region 查询并构建抽取记录的专家列表
                        var details = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract_detail>()
                            .Where(c => c.extract == record &&
                                c.IsValid == 1)
                            .OrderBy(c => c.CreateDate).Asc()
                            .OrderBy(c => c.order_flag).Asc()
                            .JoinQueryOver<DB_NH.DB_Model.ZJK.ZJ_expert>(c => c.expert)
                            .Where(exp => exp.IsValid == 1)
                            .List();

                        foreach (var _detail in details)
                        {
                            ZJK.Models.ExtractManage.ExtractExpert _exp = new ExtractExpert()
                            {
                                exp_id = _detail.expert.Id,
                                exp_mobile = _detail.zj_mobile,
                                exp_name = _detail.zj_name,
                                exp_company = _detail.zj_company,
                                exp_professon = _detail.zj_professional,
                                exp_title = _detail.zj_title,
                                exp_isOK = _detail.is_selected,
                                exp_remark = _detail.un_selected_msg,
                                exp_type = _detail.zj_type_name
                            };
                            extRecord.experts.Add(_exp);
                        }
                        #endregion

                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {

                        transaction.Rollback();
                        TempData[Common.CONST_TEMPDATA_INF] = @"操作失败，请联系管理员获取错误信息。";
                        TempData[Common.CONST_TEMPDATA_ERR] = ex.Message;
                    }
                }
            }
            return View(extRecord);
        }

        /// <summary>
        /// 另存抽取记录结果表到Excel并下载
        /// </summary>
        /// <param name="id">抽取记录ID</param>
        /// <returns></returns>
        public FileContentResult exportExtractRecordToExcel(string id)
        {
            #region 获取指定ID的抽取记录信息
            ZJK.Models.ExtractManage.vmExtractRecord extRecord = new ZJK.Models.ExtractManage.vmExtractRecord()
            {
                extractID = id,
                experts = new List<ExtractExpert>(),
                OPDate = DateTime.Now,
                OPUser = string.Empty,
                projs = new List<ExtractProject>()
            };

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    try
                    {
                        #region 查询并构建抽取记录以及关联的项目列表
                        var record = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract>()
                            .Fetch(c => c.zj_extract_projects).Eager()
                            .Where(c => c.Id == id)
                            .SingleOrDefault();

                        if (record != null && record.zj_extract_projects.Count > 0)
                        {
                            #region 设置抽取用户
                            extRecord.OPUser = record.user.user_truename_cn;
                            extRecord.OPDate = record.CreateDate;
                            #endregion

                            foreach (var _p in record.zj_extract_projects)
                            {
                                if (_p != null && _p.is_valid == 1)
                                {
                                    var _proj = new ZJK.Models.ExtractManage.ExtractProject()
                                    {
                                        proj_id = _p.proj_id,
                                        proj_code = _p.proj_code,
                                        proj_name = _p.proj_name
                                    };

                                    extRecord.projs.Add(_proj);
                                }
                            }
                        }
                        else
                        {
                            throw new Exception("记录未找到。");
                        }

                        #endregion

                        #region 查询并构建抽取记录的专家列表
                        var details = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract_detail>()
                            .Where(c => c.extract == record &&
                                c.IsValid == 1)
                            .OrderBy(c => c.CreateDate).Asc()
                            .OrderBy(c => c.order_flag).Asc()
                            .JoinQueryOver<DB_NH.DB_Model.ZJK.ZJ_expert>(c => c.expert)
                            .Where(exp => exp.IsValid == 1)
                            .List();

                        foreach (var _detail in details)
                        {
                            ZJK.Models.ExtractManage.ExtractExpert _exp = new ExtractExpert()
                            {
                                exp_id = _detail.expert.Id,
                                exp_mobile = _detail.zj_mobile,
                                exp_name = _detail.zj_name,
                                exp_company = _detail.zj_company,
                                exp_professon = _detail.zj_professional,
                                exp_title = _detail.zj_title,
                                exp_isOK = _detail.is_selected,
                                exp_remark = _detail.un_selected_msg,
                                exp_type = _detail.zj_type_name
                            };
                            extRecord.experts.Add(_exp);
                        }
                        #endregion

                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {

                        transaction.Rollback();
                        TempData[Common.CONST_TEMPDATA_INF] = @"操作失败，请联系管理员获取错误信息。";
                        TempData[Common.CONST_TEMPDATA_ERR] = ex.Message;
                    }
                }
            }
            #endregion

            //定义
            string contents = string.Empty;
            //定义临时参数
            string strTemp = string.Empty;

            #region 拼凑导出的文件正文
            #region 设置正文页眉
            contents += @"
<table style=""border: 0px #000 solid; border-collapse:collapse; width:665px"">
    <tr>
        <td ColSpan=""8"" style=""text-align: center;""><h2>抽取评委登记表</h2></td>
    </tr>
    <tr>
        <td ColSpan=""8"" style=""height: 2em;"">抽取时间：{cqsj}</td>
    </tr>
    <tr>
        <td ColSpan=""8"" style=""height: 2em;"">项目编号/名称：{xmmc}</td>
    </tr>
    <tr>
        <td style=""border: 0.5pt #000 solid; border-collapse:collapse; text-align: center; height: 2em;"">序号
        </td>
        <td style=""border: 0.5pt #000 solid; border-collapse:collapse; text-align: center; height: 2em;"">专家类型
        </td>
        <td style=""border: 0.5pt #000 solid; border-collapse:collapse; text-align: center; height: 2em;"">姓名
        </td>
        <td style=""border: 0.5pt #000 solid; border-collapse:collapse; text-align: center; height: 2em;"">工作单位
        </td>
        <td style=""border: 0.5pt #000 solid; border-collapse:collapse; text-align: center; height: 2em;"">联系方式
        </td>
        <td style=""border: 0.5pt #000 solid; border-collapse:collapse; text-align: center; height: 2em;"">职称、职务
        </td>
        <td style=""border: 0.5pt #000 solid; border-collapse:collapse; text-align: center; height: 2em;"">是否参与评标
        </td>
        <td style=""border: 0.5pt #000 solid; border-collapse:collapse; text-align: center; height: 2em;"">备注
        </td>
    </tr>";

            //设置数据正文的头部(抽取时间)
            contents = contents.Replace("{cqsj}", extRecord.OPDate.ToString("yyyy年MM月dd日HH时mm分"));

            //设置数据正文的头部(项目名称抽取时间)
            foreach (var _p in extRecord.projs)
            {
                if (string.IsNullOrEmpty(strTemp))
                {
                    strTemp = "[" + _p.proj_code + "]" + _p.proj_name;
                }
                else
                {
                    strTemp += "；[" + _p.proj_code + "]" + _p.proj_name;
                }
            }

            contents = contents.Replace("{xmmc}", strTemp);
            #endregion

            #region 设置正文专家数据
            int i = 0;
            foreach (var _exp in extRecord.experts)
            {
                i++;
                //是否参加评标
                string str1 = "是";
                string str2 = string.Empty;
                if (_exp.exp_isOK != 1)
                {
                    str1 = "否";
                    str2 = _exp.exp_remark;
                }

                //数据
                contents += @"
    <tr>
        <td style=""border: 0.5pt #000 solid; border-collapse:collapse; text-align: center; height: 2em;"">" + i.ToString() + @"
        </td>
        <td style=""border: 0.5pt #000 solid; border-collapse:collapse; text-align: center; height: 2em;"">" + _exp.exp_type + @"
        </td>
        <td style=""border: 0.5pt #000 solid; border-collapse:collapse; text-align: center; height: 2em;"">" + _exp.exp_name + @"
        </td>
        <td style=""border: 0.5pt #000 solid; border-collapse:collapse; height: 2em;"">" + _exp.exp_company + @"
        </td>
        <td style=""border: 0.5pt #000 solid; border-collapse:collapse; text-align: center; height: 2em;"">" + _exp.exp_mobile + @"
        </td>
        <td style=""border: 0.5pt #000 solid; border-collapse:collapse; text-align: center; height: 2em;"">" + _exp.exp_title + @"
        </td>
        <td style=""border: 0.5pt #000 solid; border-collapse:collapse; text-align: center; height: 2em;"">" + str1 + @"
        </td>
        <td style=""border: 0.5pt #000 solid; border-collapse:collapse; height: 2em;"">" + str2 + @"
        </td>
    </tr>";
            }
            #endregion

            #region 设置正文页脚
            contents += @"
    <tr>
        <td ColSpan=""4"" style=""height: 3em;"">抽取评委经办人（签字）:</td>
        <td ColSpan=""4"" style=""height: 3em;"">抽取评委现场监督人（签字）:</td>
    </tr>
</table>";
            #endregion

            #endregion

            byte[] fileContents = System.Text.Encoding.Default.GetBytes(contents);
            return new FileContentResult(fileContents, "application/vnd.ms-excel") { FileDownloadName = System.Web.HttpUtility.UrlEncode("抽取记录", System.Text.Encoding.UTF8) + ".xls" };

        }

        /// <summary>
        /// 根据关键字获取抽取操作第一步的项目列表
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetStep1Projects(string keyword)
        {
            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    #region 获取项目信息
                    string ss = keyword;
                    if (keyword.IndexOf('/') >= 0)
                    {
                        ss = keyword.Substring(0, keyword.IndexOf('/'));
                    }

                    var _projects = session.QueryOver<DB_NH.DB_Model.ywxt.t_project>()
                        .Where(c => c.is_valid == 1 && c.is_leaf == 1 && (
                            c.proj_code.IsLike("%" + ss) || c.proj_code.IsLike("%" + ss + "/%") || c.proj_name.IsLike("%" + ss + "%")))
                        .OrderBy(c => c.ProjectYear).Desc()
                        .OrderBy(c => c.proj_order_flag).Desc()
                        .OrderBy(c => c.proj_code).Asc()
                        .List();

                    List<vmStep1Project> projects = new List<vmStep1Project>();

                    foreach (var _proj in _projects)
                    {
                        string _proj_code = _proj.proj_code;
                        /*
                        if (_proj_code.IndexOf('/') >= 0)
                        {
                            //项目编号带有“/”，则编号截取第一个"/"字符前5位
                            _proj_code = _proj_code.Remove(0, _proj_code.IndexOf('/') - 5);
                        }
                        else
                        {
                            _proj_code = _proj_code.Remove(0, _proj_code.Length - 5);
                        }
                         */
                        vmStep1Project _p = new vmStep1Project()
                        {
                            projectId = _proj.proj_id,
                            projectCode = _proj_code,
                            projectName = _proj.proj_name
                        };

                        _p.projectExtractRecords = new List<vmStep1ProjectExtractRecord>();
                        var _extracts = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract>()
                            .Where(c => c.IsValid == 1)
                            .OrderBy(c => c.CreateDate).Desc()
                            .JoinQueryOver<DB_NH.DB_Model.ywxt.t_project>(x => x.zj_extract_projects)
                            .Where(x => x.proj_id == _proj.proj_id)
                            .List();
                        foreach (var v in _extracts)
                        {
                            vmStep1ProjectExtractRecord _extractRec = new vmStep1ProjectExtractRecord()
                            {
                                recId = v.Id,
                                recOPuserName = v.user.user_truename_cn,
                                recTitle = v.title,
                                recDate = v.extract_date.ToString("yyyy-MM-dd")
                            };
                            _p.projectExtractRecords.Add(_extractRec);
                        }

                        projects.Add(_p);
                    }

                    transaction.Commit();
                    return Json(projects, JsonRequestBehavior.AllowGet);
                    #endregion
                }
            }
        }

        #region 抽取用------------------------------------------------------------------------------
        /// <summary>
        /// 根据选取的项目ID列表（以逗号分割），新建一条空的抽取记录
        /// </summary>
        /// <param name="selectedProjectIDs">指定的项目ID列表，以逗号分割</param>
        /// <returns></returns>
        public ActionResult newExtract(string selectedProjectIDs)
        {
            string _new_record_id = string.Empty;
            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    try
                    {
                        #region 查询抽取记录关联的项目记录列表
                        string[] _p_ids = selectedProjectIDs.Split(',');
                        var _projects = session.QueryOver<DB_NH.DB_Model.ywxt.t_project>()
                            .Where(c => c.is_valid == 1 && c.proj_id.IsIn(_p_ids) && c.is_leaf == 1)
                            .OrderBy(c => c.proj_code).Asc()
                            .List();
                        if (_projects.Count <= 0)
                        {
                            throw new Exception("抽取记录关联的项目错误，没有找到关联项目。");
                        }
                        #endregion


                        string _this_user_name_en = Common.getAuthenticatedUser(User).Name;
                        string _this_user_name_cn = Common.getAuthenticatedUser(User).DisplayName;

                        var _this_user = session.QueryOver<DB_NH.DB_Model.ywxt.t_sys_user>()
                            .Where(c => c.is_valid == 1
                                && c.user_truename_en == _this_user_name_en
                                && c.user_truename_cn == _this_user_name_cn)
                            .SingleOrDefault();

                        if (_this_user == null)
                        {
                            throw new Exception("操作员信息未找到！");
                        }


                        #region 新建一条抽取记录
                        DB_NH.DB_Model.ZJCQ.ZJ_extract _new_extract = new DB_NH.DB_Model.ZJCQ.ZJ_extract();
                        _new_extract.title = "[" + _this_user.user_truename_cn + ":" +
                            DateTime.Now.ToString("yyyy-MM-dd HH:mm") + "]抽取(" +
                            _projects[0].proj_code + ")等" + _projects.Count.ToString() +
                            "个项目的评审专家";
                        foreach (var _p in _projects)
                        {
                            _new_extract.zj_extract_projects.Add(_p);
                            _p.proj_extracts.Add(_new_extract);
                        }
                        _new_extract.user = _this_user;
                        _new_extract.extract_date = DateTime.Now;
                        session.SaveOrUpdate(_new_extract);
                        #endregion

                        _new_record_id = _new_extract.Id;

                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        TempData[Common.CONST_TEMPDATA_INF] = @"操作失败，请联系管理员获取错误信息。";
                        TempData[Common.CONST_TEMPDATA_ERR] = ex.Message;
                    }
                }
            }

            return RedirectToAction("doExtract", new { extractID = _new_record_id });
        }

        /// <summary>
        /// 执行抽取操作
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult doExtract(string extractID)
        {
            ZJK.Models.ExtractManage.vmExtract model = new vmExtract();
            if (ModelState.IsValid)
            {
                var sessionFactory = SessionFactory.GetCurrentFactory();
                using (var session = sessionFactory.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {
                        try
                        {
                            //根据抽取记录ID，获取抽取记录信息，生成model
                            var _extract = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract>()
                                .Where(c => c.IsValid == 1 && c.Id == extractID)
                                .SingleOrDefault();
                            if (_extract == null)
                            {
                                throw new Exception("抽取记录错误！");
                            }

                            model.extractRecordID = _extract.Id;
                            model.extractRecordTitle = _extract.title;
                            model.extractRecordDate = _extract.extract_date.ToString("yyyy-MM-dd HH:mm");

                            //设置项目信息
                            foreach (var _project in _extract.zj_extract_projects)
                            {
                                vmProject _p = new vmProject();
                                _p.projectCode = _project.proj_code;
                                _p.projectId = _project.proj_id;
                                _p.projectName = _project.proj_name;

                                model.extractRecordSelectedProjects.Add(_p);
                            }


                            transaction.Commit();
                        }
                        catch (Exception _ex)
                        {
                            transaction.Rollback();
                            TempData[Common.CONST_TEMPDATA_INF] = @"操作失败，请联系管理员获取错误信息。";
                            TempData[Common.CONST_TEMPDATA_ERR] = _ex.Message;
                        }
                    }
                }
            }
            return View(model);
        }

        /// <summary>
        /// 执行抽取操作
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult doExtract2(string extractID)
        {
            ZJK.Models.ExtractManage.vmExtract model = new vmExtract();
            if (ModelState.IsValid)
            {
                var sessionFactory = SessionFactory.GetCurrentFactory();
                using (var session = sessionFactory.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {
                        try
                        {
                            //根据抽取记录ID，获取抽取记录信息，生成model
                            var _extract = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract>()
                                .Where(c => c.IsValid == 1 && c.Id == extractID)
                                .SingleOrDefault();
                            if (_extract == null)
                            {
                                throw new Exception("抽取记录错误！");
                            }

                            model.extractRecordID = _extract.Id;
                            model.extractRecordTitle = _extract.title;
                            model.extractRecordDate = _extract.extract_date.ToString("yyyy-MM-dd HH:mm");

                            //设置项目信息
                            foreach (var _project in _extract.zj_extract_projects)
                            {
                                vmProject _p = new vmProject();
                                _p.projectCode = _project.proj_code;
                                _p.projectId = _project.proj_id;
                                _p.projectName = _project.proj_name;

                                model.extractRecordSelectedProjects.Add(_p);
                            }


                            transaction.Commit();
                        }
                        catch (Exception _ex)
                        {
                            transaction.Rollback();
                            TempData[Common.CONST_TEMPDATA_INF] = @"操作失败，请联系管理员获取错误信息。";
                            TempData[Common.CONST_TEMPDATA_ERR] = _ex.Message;
                        }
                    }
                }
            }
            return View(model);
        }

        /// <summary>
        /// 专家抽取详细记录类定义
        /// </summary>
        public class extractDetail
        {
            /// <summary>
            /// 详细记录排序索引
            /// </summary>
            public int rowIDX { get; set; }

            /// <summary>
            /// 所属抽取记录ID
            /// </summary>
            public string eId { get; set; }

            /// <summary>
            /// 详细记录ID
            /// </summary>
            public string dId { get; set; }

            /// <summary>
            /// 当前专家是否参加评标
            /// </summary>
            public int dIsOK { get; set; }

            /// <summary>
            /// 抽取的过程信息
            /// </summary>
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public string dDescribe { get; set; }

            /// <summary>
            /// 抽取类型：专业评委还是商务评委
            /// </summary>
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public string dType { get; set; }

            /// <summary>
            /// 抽中的专家ID
            /// </summary>
            public string expId { get; set; }

            /// <summary>
            /// 专家姓名
            /// </summary>
            public string expName { get; set; }

            /// <summary>
            /// 联系电话
            /// </summary>
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public string expPhone { get; set; }

            /// <summary>
            /// 专业
            /// </summary>
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public string expProfession { get; set; }

            /// <summary>
            /// 所在单位
            /// </summary>
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public string expCompany { get; set; }

            /// <summary>
            /// 职称
            /// </summary>
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public string expTitle { get; set; }

            /// <summary>
            /// 专家所属分类ID列表，以逗号分隔
            /// </summary>
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public string expCategorysID { get; set; }

            /// <summary>
            /// 专家所属分类名称列表，以逗号分隔
            /// </summary>
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public string expCategoryNames { get; set; }
        }

        /// <summary>
        /// 抽取记录详细记录列表的返回结果JSON类
        /// </summary>
        public class JSONforExtractDetails : ZJK.Models.clsCommonJsonResult
        {
            /// <summary>
            /// 抽取详细记录
            /// </summary>
            public List<extractDetail> details { get; set; }

            public JSONforExtractDetails()
            {
                details = new List<extractDetail>();
            }
        }

        /// <summary>
        /// 抽取记录详细记录的返回结果JSON类
        /// </summary>
        public class JSONforExtractDetail : ZJK.Models.clsCommonJsonResult
        {
            /// <summary>
            /// 抽取详细记录
            /// </summary>
            public extractDetail detail { get; set; }
        }

        /// <summary>
        /// 根据抽取记录ID，获取抽取记录详细列表
        /// </summary>
        /// <param name="extractID">指定的抽无记录ID</param>
        /// <returns></returns>
        public JsonResult getExtractDetails(string extractID)
        {
            JSONforExtractDetails _returnValue = new JSONforExtractDetails();

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    try
                    {
                        #region 获取抽取信息
                        var _extract = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract>()
                            .Where(c => c.IsValid == 1 && c.Id == extractID)
                            .SingleOrDefault();

                        if (_extract == null)
                        {
                            throw new Exception("抽取记录错误。");
                        }
                        #endregion

                        #region 获取专家抽取详细记录
                        int idx = 0;
                        var _details = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract_detail>()
                            .Where(c => c.IsValid == 1 && c.extract == _extract)
                            .OrderBy(c => c.order_flag).Asc()
                            .List();
                        foreach (var _d in _details)
                        {
                            idx++;
                            extractDetail _vmdetail = new extractDetail();
                            _vmdetail.rowIDX = idx;
                            _vmdetail.eId = _extract.Id;
                            _vmdetail.dDescribe = _d.un_selected_msg;
                            _vmdetail.dId = _d.Id;
                            _vmdetail.dIsOK = _d.is_selected;
                            _vmdetail.dType = _d.zj_type_name;
                            _vmdetail.expCompany = _d.zj_company;
                            _vmdetail.expId = string.Empty;
                            _vmdetail.expName = _d.zj_name;
                            _vmdetail.expPhone = _d.zj_mobile;
                            _vmdetail.expProfession = _d.zj_professional;
                            _vmdetail.expTitle = _d.zj_title;

                            //设置专家的分类名称
                            _vmdetail.expCategoryNames = _d.zj_category_names;


                            _returnValue.details.Add(_vmdetail);
                        }

                        transaction.Commit();
                        #endregion
                    }
                    catch (Exception _ex)
                    {
                        _returnValue.ISOK = false;
                        _returnValue.MESSAGE = _ex.Message;
                        transaction.Rollback();
                    }
                }
            }

            return Json(_returnValue);
        }


        /// <summary>
        /// 获取指定ID的详细抽取记录
        /// </summary>
        /// <param name="dId"></param>
        /// <returns></returns>
        public JsonResult getExtractDetail(string dId)
        {
            JSONforExtractDetail _returnValue = new JSONforExtractDetail();

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    try
                    {
                        #region 查询指定ID的抽取详细记录
                        var _detail = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract_detail>()
                            .Where(c => c.IsValid == 1 && c.Id == dId)
                            .SingleOrDefault();

                        if (_detail == null)
                        {
                            throw new Exception("记录未找到。");
                        }

                        _returnValue.detail = new extractDetail()
                        {
                            dDescribe = _detail.un_selected_msg,
                            dId = _detail.Id,
                            dIsOK = _detail.is_selected,
                            dType = _detail.zj_type_name,
                            eId = _detail.extract.Id,
                            expId = _detail.expert.Id,
                            expName = _detail.zj_name,
                            expPhone = _detail.zj_mobile,
                            expProfession = _detail.zj_professional,
                            expTitle = _detail.zj_title,
                            rowIDX = _detail.order_flag
                        };
                        #endregion

                        transaction.Commit();
                    }
                    catch (Exception _ex)
                    {
                        _returnValue.ISOK = false;
                        _returnValue.MESSAGE = _ex.Message;
                        transaction.Rollback();
                    }
                }
            }

            return Json(_returnValue);
        }

        /// <summary>
        /// 保存当前抽取详细记录
        /// </summary>
        /// <param name="detail">抽取的详细记录</param>
        /// <returns></returns>
        public JsonResult saveExtractDetail(extractDetail detail)
        {
            ZJK.Models.clsCommonJsonResult _returnValue = new Models.clsCommonJsonResult();

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    try
                    {
                        #region 保存详细记录的修改
                        var _detail = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract_detail>()
                            .Where(c => c.IsValid == 1 && c.Id == detail.dId)
                            .SingleOrDefault();

                        if (_detail == null)
                        {
                            throw new Exception("抽取详细记录获取失败。");
                        }

                        _detail.is_selected = detail.dIsOK;

                        _detail.un_selected_msg = detail.dDescribe;
                        #endregion

                        transaction.Commit();
                    }
                    catch (Exception _ex)
                    {
                        _returnValue.ISOK = false;
                        _returnValue.MESSAGE = _ex.Message;
                        transaction.Rollback();
                    }
                }
            }

            return Json(_returnValue);
        }

        /// <summary>
        /// 抽取完成，添加一条抽取详细记录
        /// </summary>
        /// <param name="detail"></param>
        /// <returns></returns>
        public JsonResult newAExtractDetail(extractDetail detail)
        {
            ZJK.Models.clsCommonJsonResult _returnValue = new Models.clsCommonJsonResult();

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    try
                    {
                        #region 获取当前要添加的详细记录对应的抽取记录ID
                        var _extract = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract>()
                            .Where(c => c.IsValid == 1 && c.Id == detail.eId)
                            .SingleOrDefault();

                        if (_extract == null)
                        {
                            throw new Exception("抽取记录未找到。");
                        }
                        #endregion

                        #region 获取当前详细记录对应的专家
                        var _expert = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_expert>()
                            .Where(c => c.IsValid == 1 && c.Id == detail.expId)
                            .SingleOrDefault();
                        if (_expert == null)
                        {
                            throw new Exception("抽取专家未找到。");
                        }
                        #endregion

                        #region 获取当前抽取详细记录最大的序号
                        int _max_orderflag = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract_detail>()
                            .Select(c => c.order_flag)
                            .Where(c => c.IsValid == 1 && c.extract == _extract)
                            .OrderBy(c => c.order_flag).Desc()
                            .Take(1)
                            .SingleOrDefault<int>();
                        #endregion

                        #region 为当前抽取记录添加一条详细记录
                        DB_NH.DB_Model.ZJCQ.ZJ_extract_detail _detail = new DB_NH.DB_Model.ZJCQ.ZJ_extract_detail();
                        _detail.expert = _expert;
                        _detail.is_selected = detail.dIsOK;
                        _detail.extract = _extract;
                        _detail.order_flag = _max_orderflag + 1;
                        _detail.un_selected_msg = string.Empty;
                        _detail.zj_category_names = detail.expCategoryNames;
                        _detail.zj_company = detail.expCompany;
                        _detail.zj_idcard_number = _expert.zj_idcard_number;
                        _detail.zj_mail_address = _expert.zj_mail_address;
                        _detail.zj_mobile = detail.expPhone;
                        _detail.zj_name = detail.expName;
                        _detail.zj_position = _expert.zj_position;
                        _detail.zj_professional = detail.expProfession;
                        _detail.zj_sex = _expert.zj_sex;
                        _detail.zj_tele_home = _expert.zj_tele_home;
                        _detail.zj_tele_work = _expert.zj_tele_work;
                        _detail.zj_title = detail.expTitle;
                        _detail.zj_type_name = detail.dType;

                        _extract.details.Add(_detail);
                        #endregion

                        #region 保存记录
                        session.SaveOrUpdate(_extract);
                        session.SaveOrUpdate(_detail);

                        transaction.Commit();
                        #endregion
                    }
                    catch (Exception _ex)
                    {
                        _returnValue.ISOK = false;
                        _returnValue.MESSAGE = _ex.Message;
                        transaction.Rollback();
                    }
                }
            }

            return Json(_returnValue);
        }

        /// <summary>
        /// 抽取选项类
        /// </summary>
        public class extractOption
        {
            /// <summary>
            /// 抽取选项对应的抽取记录ID，根据抽取ID，可以获取抽取的信息
            /// </summary>
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public string opExtractId { get; set; }

            /// <summary>
            /// 专业
            /// </summary>
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public string opProfession { get; set; }

            /// <summary>
            /// 专家分类ID列表，以逗号分隔
            /// </summary>
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public string opCategoryIDs { get; set; }

            /// <summary>
            /// 专业类型：技术评委、商务评委
            /// </summary>
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public string opTypeName { get; set; }

            /// <summary>
            /// 专家所在区域
            /// </summary>
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public string opArea { get; set; }
        }

        /// <summary>
        /// 抽取的专家信息，用于返回备选专家
        /// </summary>
        public class extractExpert
        {
            /// <summary>
            /// 专家ID
            /// </summary>
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public string expId { get; set; }

            /// <summary>
            /// 专家索引编号名称，用于抽取时对专家姓名进行隐匿
            /// </summary>
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public string expPName { get; set; }

            /// <summary>
            /// 专家姓名
            /// </summary>
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public string expName { get; set; }

            /// <summary>
            /// 专家单位
            /// </summary>
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public string expCompany { get; set; }

            /// <summary>
            /// 专家职称
            /// </summary>
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public string expTitle { get; set; }

            /// <summary>
            /// 专家专业
            /// </summary>
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public string expProfession { get; set; }

            /// <summary>
            /// 专家分类ID列表，以逗号分隔
            /// </summary>
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public string expCategoryIDs { get; set; }

            /// <summary>
            /// 专家分类名称列表，以逗号分隔
            /// </summary>
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public string expCategoryNames { get; set; }

            /// <summary>
            /// 专家联系电话
            /// </summary>
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public string expPhone { get; set; }
        }

        /// <summary>
        /// 备选的专家项目，包含备选项目列表，备选内定项目列表
        /// </summary>
        public class BXExpertsInfo : ZJK.Models.clsCommonJsonResult
        {
            /// <summary>
            /// 抽取详细记录的备选记录
            /// </summary>
            public List<extractDetail> BXs { get; set; }

            /// <summary>
            /// 抽取详细记录的备选内定记录
            /// </summary>
            public List<extractDetail> BXNDs { get; set; }

            public BXExpertsInfo()
            {
                BXs = new List<extractDetail>();
                BXNDs = new List<extractDetail>();
            }
        }

        /// <summary>
        /// 为指定抽取选项同时获取内定专家列表和备选专家列表
        /// 操作步骤：
        /// 1、根据抽取选项，查询当前抽取记录及其详细记录；
        /// 2、根据抽取记录，查询关联的项目列表；
        /// 3、查询关联的项目的内定备选记录列表，获取最新的一条抽取内定记录；
        /// 4、获取内定记录的详细记录；
        /// 5、根据内定记录，拼凑内定专家列表（剔除去已经选择的专家）；
        /// 6、根据抽取选项，查询符合条件的专家列表，品抽备选专家列表（剔除去已经选择的专家）；
        /// 7、循环内定记录，如果不在备选专家记录列表中，删除备选专家记录列表中的记录；
        /// </summary>
        /// <param name="option">抽取选项</param>
        /// <returns></returns>
        public JsonResult getExpertsBXByThisOption(extractOption option)
        {
            BXExpertsInfo _returnValue = new BXExpertsInfo();

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    try
                    {
                        var _details_BX = new List<extractDetail>();

                        #region 1、根据抽取选项，查询当前抽取记录及其详细记录，以及已选专家的ID列表（用于查询备选专家时剔除已选的专家）；
                        var _extract = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract>()
                            .Where(c => c.Id == option.opExtractId)
                            .SingleOrDefault();

                        if (_extract == null)
                        {
                            throw new Exception("抽取记录错误！");
                        }

                        var _extract_details = _extract.details;

                        //定义并生成已选专家ID列表
                        List<string> _extract_expert_ids_YX = new List<string>();
                        foreach (var _dtl in _extract_details)
                        {
                            if (_dtl.expert != null)
                            {
                                _extract_expert_ids_YX.Add(_dtl.expert.Id);
                            }
                        }
                        #endregion

                        #region 2、根据抽取记录，查询关联的项目列表；
                        var _extract_ref_projects = _extract.zj_extract_projects;
                        List<string> _pIds = new List<string>();
                        foreach (var _p in _extract_ref_projects)
                        {
                            _pIds.Add(_p.proj_id);
                        }
                        #endregion

                        #region 3、查询关联的项目的内定备选记录列表，获取最新的一条抽取内定记录:_bak；
                        //定义最新的抽取备份记录
                        DB_NH.DB_Model.ZJCQ.ZJ_extract_bak _bak = null;

                        //逐一循环项目，获取备选抽取列表，再逐一循环，找出最新的备选记录
                        foreach (var _p in _extract_ref_projects)
                        {
                            foreach (var _b in _p.proj_extract_baks)
                            {
                                if (_bak == null)
                                {
                                    _bak = _b;
                                }
                                else
                                {
                                    if (_bak.CreateDate < _b.CreateDate && _b.IsValid == 1)
                                    {
                                        _bak = _b;
                                    }
                                }
                            }
                        }
                        #endregion

                        #region 4、根据抽取内定记录_bak，获取内定专家详细记录
                        //4.1、根据抽取选项，获取专家内定详细记录_bak_details
                        //4.1.1、根据项目查询内定专家（剔除已选专家ID）
                        var _q_getNDs = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract_detail_bak>()
                                .Select(c => c.Id)
                                .Where(c => c.IsValid == 1 && c.extract_bak == _bak && !c.expert.Id.IsIn(_extract_expert_ids_YX));

                        if (!string.IsNullOrEmpty(option.opProfession))
                        {
                            //添加专业查询条件的or
                            var professionOR = new Disjunction();
                            string[] professions = option.opProfession.Split(new char[] { ',', ';', ' ' });

                            if (professions.Length == 1)
                            {
                                _q_getNDs = _q_getNDs.And(c => c.exp_new_profession.IsLike(professions[0], MatchMode.Anywhere));
                            }
                            else if (professions.Length > 1)
                            {
                                foreach (string _p in professions)
                                {
                                    professionOR.Add(Restrictions.On<DB_NH.DB_Model.ZJCQ.ZJ_extract_detail_bak>(c => c.exp_new_profession).IsLike(_p, MatchMode.Anywhere));
                                    _q_getNDs = _q_getNDs.And(professionOR);
                                }
                            }


                        }

                        if (!string.IsNullOrEmpty(option.opCategoryIDs))
                        {
                            //添加分类查询条件的OR
                            var categoryOR = new Disjunction();
                            string[] categoryids = option.opCategoryIDs.Split(new char[] { ',', ';' });

                            DB_NH.DB_Model.ZJK.ZJ_category cate = null;
                            _q_getNDs = _q_getNDs.JoinAlias(x => x.exp_new_categorys, () => cate)
                                .Where(() => cate.Id.IsIn(categoryids));
                        }


                        //查询内定记录
                        var _bak_detail_ids_ND = _q_getNDs.List<string>().ToArray();
                        var _bak_detail_nds = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract_detail_bak>()
                            .Where(c => c.IsValid == 1
                                && c.Id.IsIn(_bak_detail_ids_ND))
                            .OrderBy(c => c.order_flag).Asc()
                            .List();
                        List<string> _nd_exp_ids = new List<string>();

                        //4.1.2、循环添加生成内定专家记录
                        foreach (var _dtl in _bak_detail_nds)
                        {
                            extractDetail _ext_detail = new extractDetail();
                            _ext_detail.dId = _dtl.Id;
                            _ext_detail.eId = _extract.Id;
                            _ext_detail.dIsOK = _dtl.is_selected;
                            _ext_detail.dType = string.Empty;
                            _ext_detail.dDescribe = _dtl.un_selected_msg;

                            _ext_detail.expCategoryNames = string.Empty;
                            _ext_detail.expCategorysID = string.Empty;
                            _ext_detail.expCompany = _dtl.expert.zj_company;
                            _ext_detail.expId = _dtl.expert.Id;
                            _ext_detail.expName = _dtl.expert.zj_name;
                            _ext_detail.expPhone = _dtl.exp_new_mobile;
                            _ext_detail.expProfession = _dtl.exp_new_profession;
                            _ext_detail.expTitle = _dtl.expert.zj_title;

                            //将符合条件的内定记录添加进入备选中（不论只是备选还是内定选中与否）
                            _details_BX.Add(_ext_detail);
                            _nd_exp_ids.Add(_ext_detail.expId);

                            if (_ext_detail.dIsOK >= 0)
                            {
                                //只有是内定的记录，才能放入内定记录列表和内定记录ID列表中
                                _returnValue.BXNDs.Add(_ext_detail);
                            }
                        }
                        #endregion

                        #region 5、根据抽取选项，查询专家信息（剔除已选择的专家记录），首先填充内定专家
                        //5。1、首先先填充已选内定记录
                        List<string> _expert_ids = new List<string>();
                        var _q_getBXs = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_expert>()
                                .Select(c => c.Id)
                                .Where(c => c.IsValid == 1 &&
                                    c.zj_city == option.opArea &&
                                    !c.Id.IsIn(_extract_expert_ids_YX) &&
                                    !c.Id.IsIn(_nd_exp_ids));

                        if (!string.IsNullOrEmpty(option.opProfession))
                        {
                            //添加专业查询条件的or
                            var professionOR = new Disjunction();
                            string[] professions = option.opProfession.Split(new char[] { ',', ';', ' ' });
                            foreach (string _p in professions)
                            {
                                professionOR.Add(Restrictions.On<DB_NH.DB_Model.ZJK.ZJ_expert>(c => c.zj_professional).IsLike(_p, MatchMode.Anywhere));
                            }

                            _q_getBXs = _q_getBXs.And(professionOR);
                        }

                        if (!string.IsNullOrEmpty(option.opCategoryIDs))
                        {
                            DB_NH.DB_Model.ZJK.ZJ_category category = null;
                            //添加分类查询条件的OR
                            string[] categoryids = option.opCategoryIDs.Split(new char[] { ',', ';' });

                            _q_getBXs = _q_getBXs.JoinAlias(x => x.zj_categorys, () => category)
                                .Where(() => category.Id.IsIn(categoryids) && category.IsValid == 1);
                        }


                        //查询内定记录
                        var _expert_ids_BX = _q_getBXs.List<string>().ToArray();
                        var experts = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_expert>()
                            .Where(c => c.IsValid == 1 &&
                                c.Id.IsIn(_expert_ids_BX) &&
                                c.zj_stop_status == DB_NH.DB_Common.ZJKConst.EXP_STOP_STATUS.USED)
                            .List();

                        //逐一循环专家列表，拼凑抽取备选记录
                        int _bak_detail_rowIDX = 0;
                        foreach (var _exp in experts)
                        {
                            //添加当前专家到备选内定专家列表
                            extractDetail _ext_detail = new extractDetail();
                            _ext_detail.dId = Common.NewID();
                            _ext_detail.eId = _extract.Id;
                            _ext_detail.dIsOK = 0;
                            _ext_detail.dType = string.Empty;
                            _ext_detail.dDescribe = string.Empty;

                            _ext_detail.expCategoryNames = string.Empty;
                            _ext_detail.expCategorysID = string.Empty;
                            _ext_detail.expCompany = _exp.zj_company;
                            _ext_detail.expId = _exp.Id;
                            _ext_detail.expName = _exp.zj_name;
                            _ext_detail.expPhone = _exp.zj_mobile;
                            _ext_detail.expProfession = _exp.zj_professional;
                            _ext_detail.expTitle = _exp.zj_title;

                            _bak_detail_rowIDX++;
                            _ext_detail.rowIDX = _bak_detail_rowIDX;

                            _details_BX.Add(_ext_detail);
                        }
                        #endregion

                        #region 6、循环查询到的备选记录_details_BX，随机填充到返回的备选记录表中
                        int row_idx = 0;
                        while (_details_BX.Count > 0)
                        {
                            int idx = new Random().Next(_details_BX.Count);
                            row_idx++;
                            extractDetail _tmp = _details_BX[idx];
                            _tmp.rowIDX = row_idx;
                            _returnValue.BXs.Add(_tmp);
                            _details_BX.RemoveAt(idx);
                        }
                        #endregion

                        transaction.Commit();
                    }
                    catch (Exception _ex)
                    {
                        _returnValue.ISOK = false;
                        _returnValue.MESSAGE = _ex.Message;
                        transaction.Rollback();
                    }
                }
            }

            return Json(_returnValue);
        }

        #endregion
    }
}